﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;

namespace BEControlCenter.Utilities
{
    public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
    {
        #region INotifyPropertyChanged implementation

        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Raise OnPropertyChanged
        /// </summary>
        /// <param name="propertyName">Property name as string: "propertyName"</param>
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }

        /// <summary>
        /// Raise OnPropertyChanged
        /// </summary>
        /// <param name="propertyExpression">Property passed as lambda: "() => property"</param>
        protected virtual void OnPropertyChanged(Expression<Func<object>> propertyExpression)
        {
            // Retrieve lambda body
            var body = propertyExpression.Body as MemberExpression;
            if (body == null)
                throw new ArgumentException("'propertyExpression' should be a member expression");

            // raise event
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(body.Member.Name);
                handler(this, e);
            }
        }

        #endregion

        # region IDisposable implementation

        abstract public void Dispose();

        #endregion
    }
}
